package com.atguigu.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.core.listener.ExcelDictDTOListener;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author Mr.xu
 * @since 2023-04-06
 */
@Slf4j
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Resource
    private RedisTemplate redisTemplate;

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void importData(InputStream inputStream) {
        log.info("Excel导入开始");
        EasyExcel.read(inputStream, ExcelDictDTO.class, new ExcelDictDTOListener(baseMapper)).sheet().doRead();
        log.info("Excel导入成功");
    }

    @Override
    // 从数据库中获取所有数据字典记录，然后将这些记录转换为ExcelDictDTO对象的列表，并返回该列表
    public List<ExcelDictDTO> listDictData() { // 定义名为listDictData的公共方法，返回一个ExcelDictDTO对象的列表
        List<Dict> dictList = baseMapper.selectList(null); // 通过调用baseMapper的selectList方法，查询数据库中的所有数据字典记录，并将结果存储在一个名为dictList的Dict对象列表中
        ArrayList<ExcelDictDTO> excelDictDTOList = new ArrayList<>(dictList.size()); // 创建一个新的ExcelDictDTO类型的ArrayList对象，名为excelDictDTOList，并初始化其大小为dictList的大小
        dictList.forEach(dict -> { // 对dictList中的每个Dict对象执行以下操作
            ExcelDictDTO excelDictDTO = new ExcelDictDTO(); // 创建一个新的ExcelDictDTO对象，名为excelDictDTO
            BeanUtils.copyProperties(dict, excelDictDTO); // 使用BeanUtils的copyProperties方法将dict对象的属性复制到excelDictDTO对象中
            excelDictDTOList.add(excelDictDTO); // 将excelDictDTO对象添加到excelDictDTOList中
        });
        return excelDictDTOList; // 返回excelDictDTOList
    }

    @Override
    public List<Dict> listByParentId(Long parentId) {
        try {
            // 首先查询redis中是否存在数据列表
            List<Dict> dictList = (List<Dict>) redisTemplate.opsForValue().get("srb:core:dictList:" + parentId);
            if (dictList != null) {
                // 如果存在则从redis中直接返回数据
                log.info("从redis中获取数据列表");
                return dictList;
            }
        } catch (Exception e) {
            log.error("redis服务器异常:" + ExceptionUtils.getStackTrace(e));
        }

        // 如果redis里不存在则从MySQL数据库查询数据
        log.info("从数据库中获取数据列表");
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("parent_id", parentId);
        List<Dict> dictList = baseMapper.selectList(dictQueryWrapper);

        // 填充hashChildren字段
        dictList.forEach(dict -> {
            // 判断当前节点是否有子节点，找到当前的dict下级有没有子节点
            boolean hasChildren = this.hasChildren(dict.getId());
            dict.setHasChildren(hasChildren);
        });

        // 将数据回写到redis
        try {
            log.info("将数据存入redis");
            redisTemplate.opsForValue().set("srb:core:dictList:" + parentId, dictList, 5, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("redis服务器异常:" + ExceptionUtils.getStackTrace(e));
        }

        // 返回数据列表
        return dictList;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {

        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("dict_code", dictCode);
        Dict dict = baseMapper.selectOne(dictQueryWrapper);
        return this.listByParentId(dict.getId());
    }

    @Override
    public String getNameByParentDictCodeAndValue(String dictCode, Integer value) {
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("dict_code", dictCode);
        Dict parentDict = baseMapper.selectOne(dictQueryWrapper);

        if (parentDict == null) {
            return "";
        }

        dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper
                .eq("parent_id", parentDict.getId())
                .eq("value", value);
        Dict dict = baseMapper.selectOne(dictQueryWrapper);

        if (dict == null) {
            return "";
        }

        return dict.getName();
    }

    @Override
    public void addCategory(Long parentId, String name) {
        // 查询是否具有该id为parentId的数据，如果没有数据，则value值为0。如果有数据，则value值为最大的value值
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("parent_id", parentId);
        Integer count = baseMapper.selectCount(dictQueryWrapper);
        Dict maxValueDict = new Dict();
        if (count == 0) {
            maxValueDict.setValue(0);
        } else {
            dictQueryWrapper = new QueryWrapper<>();
            dictQueryWrapper.eq("parent_id", parentId)
                    .orderByDesc("value")
                    .last("limit 1");
            maxValueDict = baseMapper.selectOne(dictQueryWrapper);
        }

        // 创建新字典对象
        Dict newDict = new Dict();

        // 设置父类id
        newDict.setParentId(parentId);

        // 设置子类名称
        newDict.setName(name);

        // 设置新子类的value值
        newDict.setValue(maxValueDict.getValue() + 1);

        // 插入新的子类记录
        this.save(newDict);

        // 写入redis
        redisTemplate.opsForValue().set("srb:core:dictList:" + parentId, newDict, 5, TimeUnit.MINUTES);
        System.out.println("新增数据已经更新到redis！");

        // 更新父类的hasChildren字段
        Dict parentDict = getById(parentId);
        if (parentDict != null) {
            parentDict.setHasChildren(true);
            updateById(parentDict);
            // 更新Redis中的父类数据
            redisTemplate.opsForValue().set("srb:core:dictList:" + parentId, parentDict, 5, TimeUnit.MINUTES);
        }
    }

    @Override
    public boolean removeById(Long id) {
        Dict dict = getById(id);
        if (dict != null) {
            // 从数据库中删除类别
            boolean result = super.removeById(id);

            if (result) {
                // 删除Redis中父id的数据及当前数据的id
                String key = "srb:core:dictList:" + dict.getParentId();
                redisTemplate.delete(key);
            }

            // 检查当前子类是否是父类的唯一子类
            QueryWrapper<Dict> checkWrapper = new QueryWrapper<>();
            checkWrapper.eq("parent_id", dict.getParentId());
            List<Dict> siblings = baseMapper.selectList(checkWrapper);
            if (siblings.size() == 1) {
                // 更新父类的hasChildren字段
                Dict parentDict = getById(dict.getParentId());
                if (parentDict != null) {
                    parentDict.setHasChildren(false);
                    updateById(parentDict);
                    // 更新Redis中的父类数据
                    redisTemplate.opsForValue().set("srb:core:dictList:" + dict.getParentId(), parentDict, 5, TimeUnit.MINUTES);
                }
            }
            return result;
        }
        return false;
    }

    // 判断该节点是否有子节点
    private boolean hasChildren(Long id) {
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(dictQueryWrapper);
        if (count.intValue() > 0) {
            return true;
        }
        return false;
    }

}